﻿// Serotonin -- easy-to-use image filters application
// https://code.google.com/p/serotonin/
//
// Copyright © Frank Nagl, 2012-2013
// admin@franknagl.de
//
namespace Serotonin
{
    using Helper;
    using Microsoft.Win32;
    using OptionsForms;
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Windows.Forms;

    /// <summary>Start entry point of the Serotonin Application.</summary>
    public static class Program
    {
        /// <summary> Language array. </summary>
        public static Languages L { get; private set; }

        /// <summary>The file name, where the options are saved.</summary>
        public static string OptionsFile { get; private set; }
        /// <summary>The directory, where Serotonin' options files are located. </summary>
        public static string OptionsPath;
        /// <summary>The program exe, which starts Serotonin.</summary>
        public static string ProgramExe { get; private set; }
        /// <summary>The program directory, where Serotonin is located.</summary>
        public static string ProgramPath { get; private set; }
        /// <summary>Parameter value, that determines if an update will be done.
        /// </summary>
        public const string UpdateArgument = "serotonin.makeupdate";

        /// <summary>
        /// Der Haupteinstiegspunkt für die Anwendung.
        /// </summary>
        [STAThread]
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ProgramExe = Application.ExecutablePath;
            ProgramPath =
                Directory.GetParent(Application.ExecutablePath).ToString();
            OptionsPath = Environment.GetFolderPath(
                Environment.SpecialFolder.LocalApplicationData) + "\\Serotonin\\";
            OptionsFile = OptionsPath + "options.dat";

            L = new Languages();
            // if not german OS use english language
            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName != "de")
            {
                L.Text = Languages.English;
            }

            if (args.Length == 1 && 
                args[0] == UpdateArgument && 
                VistaSecurity.IsAdmin())
            {
                AutoUpdater updater = new AutoUpdater(
                                OptionsFile,
                                "http://franknagl.de/updates/Serotonin/update.csv",
                                ProgramPath,
                                ProgramExe);
                updater.MakeUpdate();
                return;
            }

            // check (and repair) context menu entries
            if (CheckContextMenuEntries())
            {
                return;
            }

            //Creates only by very first start of Serotonin
            if (!File.Exists(OptionsFile))
            {
                CreateOptionsFile(OptionsFile);
            }            
         
            MainForm form;
            // start with parameter
            if (args.Length == 2 && args[1] == "serotonin.frank")
            {
                form = new MainForm(args[0]);
            }
            // normal start
            else
            {
                form = new MainForm();
            }

            Application.Run(form);
            //if (form.IsDisposed)
            //{
            //    return;
            //}

            //form.Show();
            //while (form.Created)
            //{
            //    //form.Processor.Render();
            //    //form.UpdateEachFrame(false);
            //    Application.DoEvents();
            //}
        }

        /// <summary>
        /// Determines whether the windows explorer context menu entries for 
        /// Serotonin are correct in windows registry.
        /// </summary>
        /// <returns>True, if contextmenu are correct.</returns>
        private static bool AreCorrectContextMenuEntries()
        {
            try
            {
                // check OPEN WITH SEROTONIN
                RegistryKey regmenu = Registry.ClassesRoot.OpenSubKey(
                    "*\\shell\\Serotonin\\Command", false);
                //If format does not already exist, return true
                if (regmenu == null)
                {
                    return false;
                }

                regmenu.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        private static bool CheckContextMenuEntries()
        {
            if (VistaSecurity.IsAdmin())
            {
                Process context = new Process
                {
                    StartInfo = {FileName = ProgramPath + "\\ContextMenu.exe"}
                };
                context.Start();
                return false;
            }

            if (AreCorrectContextMenuEntries())
            {
                return false;
            }

            if (MessageBox.Show(
                L.Text[23],
                L.Text[24],
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.Yes)
            {
                VistaSecurity.RestartElevatedForUpdate();
                return true;
            }  

            return false;
        }

        private static void CreateOptionsFile(string file)
        {
            string dir = file.Substring(0, file.LastIndexOf('\\'));
            Directory.CreateDirectory(dir);
            FileStream f = File.Create(file);
            f.Close();
            IOFile.WriteLine(file, 1, "Version;1.0", true);
            IOFile.WriteLine(file, 2, "ReleaseDate;2013-03-28", true);
            IOFile.WriteLine(file, 3, "RealtimeProcessing;true", true);
        }
    }
}
